package org.apache.cordova.updateapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import com.winner.forewide.R;

@SuppressLint("HandlerLeak")
public class UpdateApp extends CordovaPlugin {

	private CallbackContext callbackContext;

	private Activity activity;

	String newVerName = "";// 新版本名称

	int newVerCode = -1;// 新版本号

	int newVerSize = -1;// 新版大小

	ProgressDialog pd = null;

	String UPDATE_SERVERAPK = "forewide.apk";

	@Override
	public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
		if (this.cordova.getActivity().isFinishing()) {
			return true;
		}
		this.activity = cordova.getActivity();
		setCallbackContext(callbackContext);
		if ("updateapp".equals(action)) {
			updateVersion();
		} else {
			callbackContext.error(PluginResult.Status.INVALID_ACTION.toString());
			return false;
		}
		return true;
	}

	public void updateVersion() {
		if (getServerVer()) {
			int verCode = this.getVerCode(this.activity);
			if (newVerCode > verCode) {
				// 更新版本
				doNewVersionUpdate();
			} else {
				// 提示已是最新版本
				notNewVersionUpdate();
			}
		}
	}

	/**
	 * 获得版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			String packName = context.getPackageName();
			verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e("版本號獲取異常", e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			String packName = context.getPackageName();
			verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e("版本名稱獲取異常", e.getMessage());
		}
		return verName;
	}

	/**
	 * 从服务器端获得版本号与版本名称
	 * 
	 * @return
	 */
	public boolean getServerVer() {
		try {
			URL url = new URL("http://58.64.141.102:8080/AppPackage/version.js");
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod("GET");
			httpConnection.connect();
			InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
			BufferedReader bReader = new BufferedReader(reader);
			String json = bReader.readLine();
			JSONArray array = new JSONArray(json);
			JSONObject jsonObj = array.getJSONObject(0);
			newVerCode = Integer.parseInt(jsonObj.getString("versionCode"));
			newVerSize = Integer.parseInt(jsonObj.getString("apkSize"));
			newVerName = jsonObj.getString("versionName");
		} catch (Exception e) {
			e.printStackTrace();
			return true;// 如果这里改为false 则不更新会退出程序
		}
		return true;
	}

	/**
	 * 不更新版本
	 */
	public void notNewVersionUpdate() {
		String verName = this.getVerName(this.activity);
		StringBuffer sb = new StringBuffer();
		sb.append("當前版本：");
		sb.append(verName);
		sb.append("\n已是最新版本");
		Dialog dialog = new AlertDialog.Builder(this.activity).setTitle("軟件更新").setMessage(sb.toString())
				.setPositiveButton("確定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// finish();
					}
				}).create();
		dialog.setCancelable(false);
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false;
				}
			}
		});
		dialog.show();
	}

	/**
	 * 更新版本
	 */
	public void doNewVersionUpdate() {
		StringBuffer sb = new StringBuffer();
		sb.append("發現新的版本：");
		sb.append(newVerName);
		sb.append("\n是否更新");
		Dialog dialog = new AlertDialog.Builder(this.activity).setTitle("軟件更新").setMessage(sb.toString())
				.setPositiveButton("更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						pd = new ProgressDialog(activity);
						pd.setTitle("正在下載");
						pd.setMessage("請稍後...");
						pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						pd.setIcon(R.drawable.icon);
						downFile("http://58.64.141.102:8080/AppPackage/forewide.apk");
					}
				}).setNegativeButton("暫不更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// finish();
					}
				}).create();
		dialog.setCancelable(false);
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false;
				}
			}
		});
		// 显示更新框
		dialog.show();
	}

	/**
	 * 下载apk
	 */
	public void downFile(final String urlStr) {
		pd.show();
		new Thread() {
			public void run() {
				try {
					URL url = new URL(urlStr);
					HttpURLConnection client = (HttpURLConnection) url.openConnection();
					client.setRequestMethod("GET"); // 设定请求方式
					client.setDoInput(true); // 允许输入流，即允许下载
					client.setDoOutput(true); // 允许输出流，即允许上传
					client.setUseCaches(false); // 不使用缓冲
					client.connect(); // 建立到远程对象的实际连接
					InputStream is = client.getInputStream();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int charb = -1;
						int count = 0;
						while ((charb = is.read(b)) != -1) {
							fileOutputStream.write(b, 0, charb);
							count += charb;
							int size = (int) (count / (newVerSize / (1024 / 10)));
							pd.setProgress(size);
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.cancel();
			update();
		}
	};

	/**
	 * 下载完成，通过Handler将下载对话框取消
	 */
	public void down() {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		this.activity.startActivity(intent);
	}

	public CallbackContext getCallbackContext() {
		return callbackContext;
	}

	public void setCallbackContext(CallbackContext callbackContext) {
		this.callbackContext = callbackContext;
	}
}